package com.cskaoyan.order.service.impl;

import com.cskaoyan.order.dal.entitys.Order;
import com.cskaoyan.order.dal.entitys.OrderItem;
import com.cskaoyan.order.dal.entitys.Stock;
import com.cskaoyan.order.dal.persistence.OrderItemMapper;
import com.cskaoyan.order.dal.persistence.OrderMapper;
import com.cskaoyan.order.dal.persistence.StockMapper;
import com.cskaoyan.order.service.OrderPayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * @author: 杨庆
 * @since: 2022.9.24 17:23
 * @description:
 */
@Service
@Slf4j
public class OrderPayServiceImpl implements OrderPayService {

    @Autowired
    OrderMapper orderMapper;
    @Autowired
    OrderItemMapper orderItemMapper;
    @Autowired
    StockMapper stockMapper;
    @Override
    public void paySuccesssHandler(String orderId) {
        //TODO  2. 修改订单的状态 ——> 已支付
        Order order = new Order();
        order.setStatus(1);
        order.setPaymentType(1);
        Example example = new Example(Order.class);
        example.createCriteria()
                .andEqualTo("orderId",orderId);
        orderMapper.updateByExampleSelective(order,example);
        // TODO 3. 查询出订单中的所有商品条目，根据每一个商品条目下单的数量，扣减商品的锁定库存
        Example example1 = new Example(OrderItem.class);
        example1.createCriteria()
                .andEqualTo("orderId",orderId);
        List<OrderItem> orderItems = orderItemMapper.selectByExample(example1);
        // 获取数量扣减锁定的库存
        if (!CollectionUtils.isEmpty(orderItems)) {
            for (OrderItem orderItem : orderItems) {
                Integer num = orderItem.getNum();
                Long itemId = orderItem.getItemId();
                Stock stock = new Stock();
                stock.setItemId(itemId);
                stock.setLockCount(-num);
                stock.setStockCount(0L);
                stockMapper.updateStock(stock);
                log.info("支付完成：{}锁定库存扣减{}完成",orderId,num);
            }
        }

    }
}
